package de.slothsoft.commons.swing.editorview;

import java.awt.BorderLayout;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

import de.slothsoft.commons.swing.AbstractDatabaseModel;
import de.slothsoft.commons.swing.AbstractListTableModel;
import de.slothsoft.commons.swing.ITableCreator;
import de.slothsoft.commons.swing.ITableHolder;
import de.slothsoft.commons.swing.SlothsoftTableCellRenderer;
import de.slothsoft.commons.swing.TableCreatorUtil;
import de.slothsoft.commons.swing.util.JTableUtil;

public abstract class AbstractTableView<T> extends AbstractTitleView implements
		ITableHolder<T>, ITableCreator<T> {

	private static final long serialVersionUID = 1L;

	private JTable table;
	protected AbstractDatabaseModel<T> model;

	public AbstractTableView() {
		createLayout();
	}

	@SuppressWarnings("unchecked")
	private void createLayout() {
		this.table = TableCreatorUtil.buildTable(this, this);
		this.model = (AbstractDatabaseModel<T>) this.table.getModel();
		add(createToolBar(), BorderLayout.NORTH);
		performSelectionChanged();
	}

	@Override
	public void performDoubleClick() {
		T selected = getSelectedElement();
		if (selected != null) {
			getEditorViewParent().openEditor(selected);
		}
	}

	@Override
	public abstract AbstractDatabaseModel<T> createModel();

	@Override
	public void refresh() {
		this.model.refresh();
	}

	@Override
	public JTable getTable() {
		return this.table;
	}

	@Override
	public AbstractListTableModel<T> getModel() {
		return this.model;
	}

	@Override
	public T getSelectedElement() {
		return JTableUtil.getSelectedElement(this.table, this.model);
	}

	@Override
	public List<T> getSelectedElements() {
		return JTableUtil.getSelectedElements(this.table, this.model);
	}

	@Override
	public JComponent createFilterComponent() {
		return null; // to be overriden
	}

	@Override
	public JComponent createInformationComponent() {
		return null; // to be overriden
	}

	@Override
	public void performSelectionChanged() {
		// to be overriden
	}

	@Override
	public TableCellRenderer createRenderer() {
		return new SlothsoftTableCellRenderer(); // to be overriden
	}

	@Override
	public int[] createColumnWidths() {
		return null; // to be overriden
	}
}